package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;


    /**
     * 新增菜品和口味
     *
     * @param dishDTO
     */
    @Override
    @Transactional//添加事务
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        //1.像菜品表中插入1条数据
        dishMapper.insert(dish);

        //获取菜品id
        Long dishId = dish.getId();

        //2.向口味表中插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
            }
            // 批量插入菜品口味数据
            dishFlavorMapper.insertBatch(flavors);

        }


    }


    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Override
    public void removeBatch(List<Long> ids) {
        //1.起售的菜品不能删除
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //2.被关联的菜品不能删除 setmeal_dish   select setmeal_id from setmeal_dish where dish_id =${dish_id}
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getDishId, ids);
        // 检查 setmeal_dish 表中是否存在关联
        Long relatedCount = setmealDishMapper.selectCount(queryWrapper);

        if (relatedCount > 0) {
            // 如果存在关联，抛出异常
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        //3.删除菜品表中的数据
        dishMapper.deleteBatchIds(ids);
        //4.删除口味表中的数据
        // 4. 删除口味表中的数据
        LambdaQueryWrapper<DishFlavor> flavorQueryWrapper = new LambdaQueryWrapper<>();
        flavorQueryWrapper.in(DishFlavor::getDishId, ids); // 根据菜品 ID 删除对应的口味数据
        dishFlavorMapper.delete(flavorQueryWrapper);

//        for (Long id : ids) {
//            dishMapper.deleteById(id);
//        }
    }


    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //1.查询菜品数据
        Dish dish = dishMapper.selectById(id);

        //2.查询菜品口味数据
        List<DishFlavor> flavors = dishFlavorMapper
                .selectList(new LambdaQueryWrapper<DishFlavor>()
                        .eq(DishFlavor::getDishId, id));

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 修改菜品起售停售
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        // 使用 LambdaUpdateWrapper 构建更新条件
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(Dish::getId, id) // 根据 ID 更新
                .set(Dish::getStatus, status) // 更新状态字段
                .set(Dish::getUpdateTime, LocalDateTime.now()) // 更新更新时间
                .set(Dish::getUpdateUser, BaseContext.getCurrentId()); // 更新更新人

        dishMapper.update(null, updateWrapper);
        if (status == StatusConstant.DISABLE) {
            stopSetmealsContainingDish(id);
        }
    }


    /**
     * 修改菜品和口味
     * @param dishDTO
     */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.updateById(dish);

        // 删除菜品口味数据
        LambdaUpdateWrapper<DishFlavor> queryWrapper =  new LambdaUpdateWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDTO.getId());
        dishFlavorMapper.delete(queryWrapper);
        //重新保存菜品口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishDTO.getId());
            }
            // 批量插入菜品口味数据
            dishFlavorMapper.insertBatch(flavors);
        }


    }


    /**
     * 根据菜品分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        // 使用 LambdaQueryWrapper 构建查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Dish::getCategoryId, categoryId) // 根据分类 ID 查询
                .eq(Dish::getStatus, StatusConstant.ENABLE) // 查询启售状态的菜品
                .orderByDesc(Dish::getUpdateTime); // 根据更新时间倒序排序
        // 执行查询并返回结果
        return dishMapper.selectList(queryWrapper);
    }

    /**
     * 根据菜品分类id查询菜品和口味信息
     *
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        //动态查询菜品数据
        // 使用 LambdaQueryWrapper 构建查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Dish::getCategoryId, dish.getCategoryId()) // 根据分类 ID 查询
                .eq(Dish::getStatus, StatusConstant.ENABLE) // 查询启售状态的菜品
                .orderByDesc(Dish::getUpdateTime); // 根据更新时间倒序排序

        List<Dish> dishList = dishMapper.selectList(queryWrapper);

        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);
            List<DishFlavor> flavors = dishFlavorMapper.selectList(new LambdaQueryWrapper<DishFlavor>()
                            .eq(DishFlavor::getDishId, d.getId()));
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return  dishVOList;
    }


    /**
     * 停售包含指定菜品的套餐
     *
     * @param dishId 菜品 ID
     */
    private void stopSetmealsContainingDish(Long dishId) {
        // 获取包含该菜品的套餐 ID 列表
        List<Long> dishIds = Collections.singletonList(dishId);
        // 使用 LambdaQueryWrapper 查询关联的套餐 ID 列表
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .select(SetmealDish::getSetmealId) // 只查询套餐 ID 字段
                .in(SetmealDish::getDishId, dishIds); // 根据菜品 ID 列表查询
        // 执行查询并获取套餐 ID 列表
        List<Long> setmealIds = setmealDishMapper.selectObjs(queryWrapper)
                .stream()
                .map(obj -> (Long) obj) // 将 Object 转换为 Long
                .collect(Collectors.toList());


        if (setmealIds != null && !setmealIds.isEmpty()) {
            // 使用 LambdaUpdateWrapper 批量更新套餐状态
            LambdaUpdateWrapper<Setmeal> setmealUpdateWrapper = new LambdaUpdateWrapper<>();
            setmealUpdateWrapper
                    .in(Setmeal::getId, setmealIds) // 根据套餐 ID 更新
                    .set(Setmeal::getStatus, StatusConstant.DISABLE); // 更新状态为停售

            // 调用 MyBatis-Plus 的 update 方法
            setmealMapper.update(null, setmealUpdateWrapper);
        }
    }


}




